from flask_pw import Peewee
from flask_sqlalchemy import SQLAlchemy

TABLE_PREFIX = 'vsg'

db = SQLAlchemy()
class ModelMixin():
    # updated_at = DateTimeField(db_column='update_at', help_text='更新时间')
    # created_at = DateTimeField(db_column='created_at', help_text='创建时间', default=datetime.datetime.now)

    @classmethod
    def atomic(cls):
        return getattr(getattr(cls, '_meta'), 'database').atomic()

    # def atomic(self):
    #     return getattr(getattr(self, '_meta'), 'database').atomic()

    class Meta:
        only_save_dirty = True


        # @ModelMixin.pre_save.connect
        # def pre_save_handler(instance, created):
        #     if created:
        #         if hasattr(instance, '_meta'):
        #             meta = getattr(instance, '_meta')
        #             if meta.primary_key and isinstance(meta.primary_key, PrimaryKeyField):
        #                 name = getattr(meta.primary_key, 'name')
        #                 if getattr(instance, name) is None:
        #                     setattr(instance, name, next_id(meta.table_alias or meta.db_table))
        #
        #     setattr(instance, 'updated_at', datetime.datetime.now())
        #
        #
        # class Model(Model_):
        #     updated_at = DateTimeField(db_column='updated_at', help_text='更新时间')
        #     created_at = DateTimeField(db_column='created_at', help_text='创建时间', default=datetime.datetime.now)
        #
        #     @classmethod
        #     def first(cls, *args, **kwargs):
        #         try:
        #             return super().get(*args, **kwargs)
        #         except DoesNotExist as _igorer:
        #             return None
        #
        #     class Meta:
        #         only_save_dirty = True
        #
        #     @classmethod
        #     def atomic(cls):
        #         return getattr(getattr(cls, '_meta'), 'database').atomic()

        # def atomic(self):
        #     return getattr(getattr(self, '_meta'), 'database').atomic()

        # @classmethod
        # def get_or_none(cls, *args, **kwargs):
        #     return cls.first(*args, **kwargs)


# from   .contril import  PaymentService
#
# payment_service  = PaymentService()
#
#
# def next_id(code=None):
#     class TableSeq(database.Model):
#         code = CharField(primary_key=True, max_length=40)
#         seq = IntegerField(default=0)
#
#         class Meta:
#             db_table = '{}_table_seqs'.format(TABLE_PREFIX)
#
#         @classmethod
#         def get_seq(cls, code):
#             import random
#             code = code or 'id_seq'
#             with database.database.transaction() as  txn:
#                 seq, created = TableSeq.get_or_create(code=code,
#                                                       defaults={
#                                                           'code': code,
#                                                           'seq': random.randint(10000, 999999)
#                                                       })
#                 next_id = seq.seq + 1
#                 TableSeq.update(seq=next_id).where(TableSeq.code == code).execute()
#
#                 txn.commit()
#                 return next_id
#
#     return TableSeq.get_seq(code)
#

#
# @pre_save(sender=Model)
# def on_pre_save(instance, model, created):
#     if created:
#         if hasattr(instance, '_meta'):
#             meta = getattr(instance, '_meta')
#             if meta.primary_key and isinstance(meta.primary_key, PrimaryKeyField):
#                 name = getattr(meta.primary_key, 'name')
#                 if getattr(model, name) is None:
#                     setattr(model, name, next_id(meta.table_alias or meta.db_table))
#
#     setattr(model, 'updated_at', datetime.datetime.now())
#
# #
# class Model(Peewee.Model):
#     @staticmethod
#     def first(cls, *query, **kwargs):
#         try:
#             return cls.get(query, kwargs)
#         except DoesNotExist:
#             return None

database = Peewee()
